package com.hr.service.impl;

import com.hr.utils.JwtUtils;
import com.sun.xml.bind.v2.TODO;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import com.hr.domain.dto.MessageDTO;
import com.hr.utils.UserContext;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Component
@AllArgsConstructor
public class ChatMemoryImpl implements ChatMemory {

    private RedisTemplate<String, Object> redisTemplate;
    //定义缓存Key的前置
    private static final String CHAT_MEMORY_KEY = "chat_memory:";

    private static final int maxSize = 15;

    private static final long ttlSeconds = 60 * 60 * 24;

    private Message toMessage(MessageDTO dto) {
        String role = dto.getRole();
        String content = dto.getContent();

        if ("user".equalsIgnoreCase(role)) {
            return new UserMessage(content);
        } else if ("assistant".equalsIgnoreCase(role)) {
            return new AssistantMessage(content);
        } else if ("system".equalsIgnoreCase(role)) {
            return new SystemMessage(content);
        } else {
            // 默认当作用户消息处理或抛异常
            return new UserMessage(content);
        }
    }
    /**
     * 获取用户ID
     * @param conversationId 会话ID
     */
    private Long extractUserId(String conversationId) {
        if (conversationId == null || !conversationId.contains(":")) {
            throw new IllegalArgumentException("conversationId格式不对: " + conversationId);
        }
        String[] parts = conversationId.split(":", 2); // 只 split 一次，避免 chatId 中有冒号
        return Long.valueOf(parts[0]);
    }
    /**
     * 获取会话ID
     * @param conversationId 会话ID
     */
    private String extractChatId(String conversationId) {
        return conversationId.split(":", 2)[1];
    }

    /**
     * 添加会话记录
     * @param conversationId 会话ID
     * @param messages 会话记录
     */
    @Override
    public void add(String conversationId, List<Message> messages) {

        Long userId = extractUserId(conversationId);

        String chatId = extractChatId(conversationId);

        String key = CHAT_MEMORY_KEY + "user:" + userId + ":chatId:" + chatId;

        //将List<Message> messages的Message对象转换为MessageDTO对象，
        // 此处转换为MessageDTO对象，是为了为了减少序列化的问题
        List<MessageDTO> messageDtos = messages.stream()
                .map(message -> {
                    MessageDTO dto = new MessageDTO();
                    dto.setRole(message.getMessageType().name().toLowerCase());
                    dto.setContent(message.getText());

                    // 如果需要，还可以设置时间戳等：
                    // dto.setTimestamp(System.currentTimeMillis());
                    return dto;
                })
                .collect(Collectors.toList());

        //使用RedisTemplate进行缓存操作，采用List集合存储（重点错误！！！！！）
        /*redisTemplate.opsForList().rightPushAll(key, messageDtos);*/
        // 关键：使用rightPushAll逐个添加元素（而非添加整个List）
        messageDtos.forEach(dto -> redisTemplate.opsForList().rightPush(key, dto));

        redisTemplate.expire(key, ttlSeconds, TimeUnit.SECONDS);
        //保留最近的maxSize条数据
        redisTemplate.opsForList().trim(key, -maxSize, -1);

    }

    /**
     * 获取会话记录
     * @param conversationId 会话ID
     * @param lastN 获取最近N条记录
     * @return
     */
    @Override
    public List<Message> get(String conversationId, int lastN) {
        //判断lastN是否小于等于0
        if (lastN <= 0) {
            return Collections.emptyList();
        }
        Long userId = extractUserId(conversationId);

        String chatId = extractChatId(conversationId);

        String key = CHAT_MEMORY_KEY + "user:" + userId + ":chatId:" + chatId;
        //获取缓存数据
        List<Object> rangeMessage = redisTemplate.opsForList().range(key, -lastN, -1);
        //判断数据是否为空
        if (rangeMessage == null || rangeMessage.isEmpty()) {
            return Collections.emptyList();
        }
        return rangeMessage.stream()
                .filter(obj -> obj instanceof MessageDTO) // 安全过滤
                .map(obj -> (MessageDTO) obj)
                .map(this::toMessage) // 转换为 Spring AI 的 Message
                .collect(Collectors.toList());
    }

    /**
     * 清空会话记录
     * @param conversationId 会话ID
     */
    @Override
    public void clear(String conversationId) {
        Long userId = extractUserId(conversationId);

        String chatId = extractChatId(conversationId);

        String key = CHAT_MEMORY_KEY + "user:" + userId + ":chatId:" + chatId;
        redisTemplate.delete(key);
    }
}
